﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace PPP.Converter {
    /// <summary>
    /// One-way converter from System.Drawing.Image to System.Windows.Media.ImageSource
    /// </summary>
    [ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))]
    public class ImageToSourceConverter : IValueConverter {
        public object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture) {
            return null;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {

            int quality = 100;
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            ImageCodecInfo jpegCodec = GetEncoderInfo(@"image/jpeg");

            EncoderParameters encoderParams
            = new EncoderParameters(1);

            encoderParams.Param[0] = qualityParam;

            // empty images are empty
            if (value == null) { return null; }

            Bitmap image = (System.Drawing.Bitmap)value;

            Graphics graphic = null;
            // create a new bitmap object of the same height and width of the image
            Bitmap newImage = new Bitmap(image.Width, image.Height);
            graphic = Graphics.FromImage(newImage);

            graphic.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            
            // winforms image we want to get the wpf image from
            var bitmap = new System.Windows.Media.Imaging.BitmapImage();
            bitmap.BeginInit();
            MemoryStream memoryStream = new MemoryStream();
            // save to a memory stream
            newImage.Save(memoryStream, jpegCodec, encoderParams);
            // rewind the stream
            memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
            bitmap.StreamSource = memoryStream;
            bitmap.EndInit();
            return bitmap;

        }

        /// <summary>
        /// Get the correct image codec info type
        /// </summary>
        /// <param name="mimeType">the mome type</param>
        /// <returns>image codec info</returns>
        private static ImageCodecInfo GetEncoderInfo(string mimeType) {
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < encoders.Length; i++) {
                if (encoders[i].MimeType == mimeType)
                    return encoders[i];
            }
            return null;
        }
    }
}
